#include <GL/glew.h>
#include "Trackball.h"
#include "Vector3.h"
#include <math.h>
#include "UtilGL.h"

using namespace prog3d;
using namespace std;

Trackball::Trackball() {
  orientation.setIdentity();
  started=false;
}

void Trackball::init(int x,int y) {
  cx=x;cy=y;
}

void Trackball::start(int x,int y) {
  started=true;

  xStart=x;
  yStart=y;
  orientationStart.set(orientation);
}

void Trackball::stop() {
  started=false;
}

void Trackball::motion(int x,int y) {
  if (started) {
  double angleY=x-xStart;
  double angleX=y-yStart;
  Quaternion q1;
  q1.setIdentity();
  q1.setFromAngleAxis(angleY,Vector3(0,1,0));
  orientation=orientationStart*q1;
  q1.setFromAngleAxis(angleX,Vector3(1,0,0));
  orientation=q1*orientation;
  orientation.normalize();
  }
}

bool Trackball::isStarted() {
  return started;
}

void Trackball::applyGL() {
  Vector3 u;
  double angle;
  orientation.copyToAngleAxis(&angle,&u);
//  cout << "angle=" << angle << endl;
//  cout << "axe=" << u << endl;
//  glRotatef(-angle*180.0/M_PI,u.x(),u.y(),u.());

  glRotatef(angle,u.x(),u.y(),u.z());

}


